import React, { Component, PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { actions } from 'mirrorx';
import moment from 'moment'
import { InputNumber, Select, Form, FormControl, Table, Message, Icon, Upload, Popconfirm } from 'tinper-bee';
import Radio from 'bee-radio';
import queryString from 'query-string';
import Grid from 'components/Grid';
import FormList from 'components/FormList';
import Header from 'components/Header';
import DatePicker from 'bee-datepicker';
import cloneDeep from 'lodash.clonedeep';
import Button from 'components/Button';
import CollapsePanel from 'components/CollapsePanel';
import DelModal from 'components/DelModal';
import Alert from 'components/Alert';
import FormError from 'components/FormError';
import ButtonRoleGroup from 'components/ButtonRoleGroup';
import { PurchaseApprovalButton } from 'components/PurchaseApproval';
import RefComponent from 'components/RefComponent'
import PopupModal from '../PopupModal';
import AcGrids from 'components/AcEditGrid';
import 'ac-editor/dist/index.css';
const EditGrid = AcGrids.EditGrid;
import { childTableColumn, FormField, FormTableField, SelectCode } from '../InitTemplate';


import {
    deepClone, Info, getPageParam, onHandleChildObj, renderRadioInit, CalcuParmForRef,
    initValueString, isEmptyObj, getUUI, renderSelectInit,
    onChangeSelect, resetOfferRefCommon, onEditGridValidate, ControlCommonFor1909
} from "utils";
import './index.less';

const FormItem = FormList.Item;
const format = "YYYY-MM-DD HH:mm:ss";
let { RangePicker } = DatePicker;

class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentlist: [],
            refStateParam: {},
            tableHeight: 0,
            selectedIndex: 0, //默认选中行
            editModelVisible: false,
            btnFlag: 0,
            delModalVisible: false, //删除弹框
            showHoverContent: false,
            activeKey: '1',
            childTableColumn: childTableColumn,
            FormField: FormField,
            FormTableField: {}
        }

    }

    componentWillMount(){
        actions.ActivityPlanTemplate.getAuth();
    }

    componentDidMount() {
        //计算表格滚动条高度
        sessionStorage.removeItem("errorFields");
        let searchObj = queryString.parse(this.props.location.search);
        let { btnPageFlag, search_id,getDealFlag } = searchObj;
        let self = this;
        let data;
        // if (btnPageFlag == 3) {
        //     data = { id: search_id, type: "0" };
        // } else {
        //     data = { id: search_id, type: "1" };
        // }
        let param = {
            data: search_id,
            callback: (rowData) => {
                if(btnPageFlag == 3) {
                    rowData = this.copyDataDeal(rowData);
                }
                if(rowData.customerCategoryCode == "03"){
                    if(btnPageFlag == 2){
                        this.setState({btnPageFlag : 5})
                    }else if(btnPageFlag == 1){
                        this.setState({btnPageFlag : 4})
                    }
                }
                self.initFilterFactory(rowData, btnPageFlag);
            }
        }
        if (btnPageFlag != 0) {
            actions.ActivityPlanTemplate.queryDetail(param);
        } else {
            getUUI();
            let personData = JSON.parse(localStorage.getItem("loginUserInfo")||"{}");
            let {organization=[]} = personData
            organization = organization[0] || {};
            let rowData = {
                organizationId: organization.organizationId,
                organizationName: organization.organizationName,
                organizationCode: organization.organizationCode,
            };
            if(getDealFlag) {
                rowData = this.props.rowData;
            }
            this.initFilterFactory(rowData, btnPageFlag);
            actions.ActivityPlanTemplate.updateState({ rowData: rowData, newRowData: {} });
            this.props.form.resetFields();
        }
        if (SelectCode && SelectCode.length > 0) {
            actions.ActivityPlanTemplate.getSelectData(SelectCode);
        }
        this.setState({ btnPageFlag, search_id, childTableColumn, FormField, FormTableField });

    }

    /**
     *
     * @param {Number} pageIndex 跳转指定页数
     */
    freshData = (pageIndex) => {
        this.onPageSelect(pageIndex, 0);
    }

    /**
     *
     * @param {*} index 跳转指定页数
     * @param {*} value 设置一页数据条数
     */
    onDataNumSelect = (index, value) => {
        this.onPageSelect(value, 1);
    }

    onBack = async () => {
        actions.routing.push(
            {
                pathname: '/ActivityPlanTemplate-list',
            }
        )
    }

    handleAssin = (newRowData = {}, values) => {
        //let param = Object.assign({}, newRowData, values);
        Object.keys(values).forEach(function (item) {
            if (isEmptyObj(values[item])) {
                values[item] = Object.assign({}, newRowData[item], values[item]);
                !values[item].id ? values[item].persistStatus = 'new' : values[item].persistStatus = 'upd';
                if (!(newRowData[item] instanceof Array) && values[item].id) {
                    values[item].customerId = newRowData.id;
                }
            }
        })
        values = Object.assign({}, newRowData, values);
        return values;
    }


    onEditGridChange = (data, childType, operObj, error) => {
        let { rowData } = this.props;
        if (operObj.operType == "edit") {
            let index = operObj.index;
            let unitPrice = parseFloat(data[index].unitPrice || 0);  //单价
            let planSaleNum = parseFloat(data[index].planSaleNum || 0);  //计划销售台量
            let discountSingle = parseFloat(data[index].discountSingle || 0);  //折让-单台（元/台）
            let discountSingleAppend = parseFloat(data[index].discountSingleAppend || 0);  //折让-开单提成（元/台）
            let discountSaleCost = parseFloat(data[index].discountSaleCost/100 || 0);  //折让-销售费用%
            let discountReserveCost = parseFloat(data[index].discountReserveCost/100 || 0);  //折让-预留费用%
            let salaryWithOrder = parseFloat(data[index].salaryWithOrder || 0);  //薪资-带单（元/台）
            let salaryTransferCommission = parseFloat(data[index].salaryTransferCommission || 0);  //薪资-变动提成（元/台）
            let salarySaleInspire = parseFloat(data[index].salarySaleInspire/100 || 0);  //薪资-销售激励%
            let wireSingleInspire = parseFloat(data[index].wireSingleInspire || 0);  //电汇-单台激励（元/台）
            let wireSaleInspire = parseFloat(data[index].wireSaleInspire/100 || 0);  //电汇-销售激励%
            data[index].planSaleAmount =  parseFloat(unitPrice*planSaleNum).toFixed(2);  //计划销售额（元）
            data[index].discountTotal =  parseFloat((discountSingle+discountSingleAppend)*planSaleNum+((discountSaleCost+discountReserveCost)*data[index].planSaleAmount)).toFixed(2);  //折让-小计（元）
            data[index].salaryTotal =  parseFloat((salaryWithOrder+salaryTransferCommission)*planSaleNum+(salarySaleInspire*data[index].planSaleAmount)).toFixed(2);  //薪资-小计（元）
            data[index].wireTransfer =  parseFloat(wireSingleInspire*planSaleNum+(wireSaleInspire*data[index].planSaleAmount)).toFixed(2);  //电汇-小计（元）
            data[index].planCostAmountTotal =  parseFloat(Number(data[index].discountTotal)+Number(data[index].salaryTotal)+Number(data[index].wireTransfer)).toFixed(2);  //计划费用额合计（元）
            data[index].planCostRate =  data[index].planSaleAmount==0.00?0.00:parseFloat(data[index].planCostAmountTotal/data[index].planSaleAmount*100).toFixed(2);  //计划销售额（元）
            data[index].planReimburseAmount =  parseFloat(Number(data[index].discountTotal)+Number(data[index].wireTransfer)).toFixed(2);  //计划报销额合计 （元）
        }
        rowData[childType] = data;
        
        data = data.filter(item => {
            return item.persistStatus != "fdel";
        })

        actions.ActivityPlanTemplate.updateState({ rowData: rowData });
    }


    onEditGridDel = (data) => {

    }

    save = () => {//保存
        let _this = this;
        let { childTableColumn } = this.state;
        sessionStorage.removeItem("errorFields");
        Object.keys(childTableColumn).forEach(function (item) {
            if (childTableColumn[item].type == "grid") {
                childTableColumn[item].column.map(childItem => {
                    if (typeof childItem.validate == "boolean"  && !childItem.hideField) {
                        childItem.validate = true;
                    }
                })
            }
        })
        this.setState(childTableColumn, () => {
            let errorFields = JSON.parse(sessionStorage.getItem("errorFields"));
            let err = false;
            errorFields && Object.keys(errorFields).forEach(function (item) {
                if (errorFields[item]) {
                    err = item;
                    return;
                }
            })

            if (!err) {
                _this.formDataDeal()
            } else {
                Message.create({ content: `明细字段:行${err} 校验不通过`, color: 'warning', duration: 10 });
                return;
            }
        });
    }

    veriryUniqData0 = (data, field) => {
        let error = false;
        var count = 0;
        if (!data || data.length <= 1) return error;
        data = data.filter(function(item) {
            return item.persistStatus != "fdel";
        });
        data.map((item, index) => {
            count += item[field]
        })
        return (count > 1);
    }

    veriryUniqData = (data, field) => {
        let error = false;
        if (!data || data.length <= 1) return error;
        data = data.filter(function(item) {
            return item.persistStatus != "fdel";
        });
        data.map((item1, index1) => {
            data.map((item2, index2) => {
                if (index1 != index2 && item2[field] && item1[field] == item2[field]) {
                    error = true
                }
            })
        })
        return error;
    }

    veriryUniqData1 = (data, field, field1) => {
        let error = false;
        if (!data || data.length <= 1) return error;
        data = data.filter(function(item) {
            return item.persistStatus != "fdel";
        });
        data.map((item1, index1) => {
            data.map((item2, index2) => {
                if (index1 != index2 && item2[field] && item1[field] == item2[field]) {
                    if (item2[field1] && item1[field1] == item2[field1])
                        error = true
                }
            })
        })
        return error;
    }

    veriryUniqData2 = (data, field, field1, field2) => {
        let error = false;
        if (!data || data.length <= 1) return error;
        data = data.filter(function(item) {
            return item.persistStatus != "fdel";
        });
        data.map((item1, index1) => {
            data.map((item2, index2) => {
                if (index1 != index2 && item2[field] && item1[field] == item2[field] && item2[field1] && item1[field1] == item2[field1]) {
                    if (item2[field2] && item1[field2] == item2[field2])
                        error = true
                }
            })
        })
        return error;
    }

    formDataDeal = () => {//保存
        let { rowData } = this.props;
        let { btnPageFlag } = this.state;

        let _this = this;
        // let btnsaveRef = ReactDOM.findDOMNode(this.refs.saveRef);
        // btnsaveRef.disabled = true;
        _this.props.form.validateFields(async (err, values) => {
            //处理保存的数据
            let data;
            data = onHandleChildObj(values, btnPageFlag, err);
            values = data.values;
            err = data.err;

            //整合table字表与表单
            let param;
            param = this.handleAssin(rowData, values);

            if(sessionStorage.getItem("uui") && btnPageFlag == "0") {
                param.id = sessionStorage.getItem("uui");
            }
            let activityPlanTemplateDetails = param.activityPlanTemplateDetails.filter(item=>{
                return item.persistStatus != "fdel";
            })
            //删除的明细，不传给后端
            if(btnPageFlag==0){
                param.activityPlanTemplateDetails = activityPlanTemplateDetails;
            }
            if(!activityPlanTemplateDetails || activityPlanTemplateDetails.length==0) {
                Message.create({ content: '明细必填一条', color: 'warning', duration: 10 });
                return;
            }
            let tooltipflag;
            activityPlanTemplateDetails.map((item1,index1)=>{
                activityPlanTemplateDetails.map((item2,index2)=>{
                  if(index1 == index2) return;
                  if(item1.activityId == item2.activityId) {
                    tooltipflag=2;
                  }
                })
            })
            if(tooltipflag&&tooltipflag==2){
                Message.create({ content: "表体活动项重复，请删除重复的活动项！", color: 'warning', duration: 5 });
                return;
            }
            if (err) {
                Message.create({ content: '必填项未填', color: 'warning', duration: 10 });
            } else {
                if (btnPageFlag == 1) {
                    await actions.ActivityPlanTemplate.updateToNCC(
                        { param: param, callback: _this.saveCallBack }
                    );
                } else {
                    await actions.ActivityPlanTemplate.save(
                        { param: param, callback: _this.saveCallBack }
                    );
                }
            }
            // btnsaveRef.disabled = false;
        });
    }

    saveCallBack = (data) => {
        let { btnPageFlag } = this.state;
        let tempFlag = btnPageFlag; 
        this.initFilterFactory(data, tempFlag);
        this.setState({btnPageFlag:tempFlag,search_id:data.id});
        // let param = {
        //     data: data[0].id,
        //     callback: (rowData) => {
        //         if(rowData.customerCategoryCode == "03"){
        //             if(btnPageFlag == 4){
        //                 tempFlag = 5;
        //             }
        //         }else{
        //             tempFlag = 2;
        //         }
        //         this.initFilterFactory(rowData, tempFlag);
        //         this.setState({btnPageFlag:tempFlag,search_id:data.id});
        //     }
        // }
        // actions.ActivityPlanTemplate.queryDetail(param);
        
    }

    copyDataDeal = (data) => {
        delete data.id;
        delete data.code;
        data.persistStatus = "new";
        // if (isEmptyObj(data.mrjtCustomerCompanyDataHeader)) {
        //     delete data.mrjtCustomerCompanyDataHeader.id;
        //     delete data.mrjtCustomerCompanyDataHeader.customerId;
        //     data.mrjtCustomerCompanyDataHeader.persistStatus = "new";
        // }
        // if (isEmptyObj(data.mrjtCustomerCredit)) {
        //     delete data.mrjtCustomerCredit.id;
        //     delete data.mrjtCustomerCredit.customerId;
        //     data.mrjtCustomerCredit.persistStatus = "new";
        // }
        if (data.mrjtCustomerAddressList && data.mrjtCustomerAddressList.length > 0) {
            data.mrjtCustomerAddressList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerContactList && data.mrjtCustomerContactList.length > 0) {
            data.mrjtCustomerContactList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerAccountList && data.mrjtCustomerAccountList.length > 0) {
            data.mrjtCustomerAccountList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerFinanceList && data.mrjtCustomerFinanceList.length > 0) {
            data.mrjtCustomerFinanceList.map(item => {
                delete item.id;
                item.persistStatus = "new";
            })
        }
        if (data.relateCustomerList && data.relateCustomerList.length > 0) {
            data.relateCustomerList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerMaterialsUsedList && data.mrjtCustomerMaterialsUsedList.length > 0) {
            data.mrjtCustomerMaterialsUsedList.map(item => {
                delete item.id;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerChangeHistoryList && data.mrjtCustomerChangeHistoryList.length > 0) {
            data.mrjtCustomerChangeHistoryList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerRankList && data.mrjtCustomerRankList.length > 0) {
            data.mrjtCustomerRankList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        return data;
    }


    // 动态显示标题
    onChangeHead = (btnPageFlag) => {
        let titleArr = ["新增", "编辑", "详情", "复制","编辑","详情"];
        return titleArr[btnPageFlag] || '新增';
    }

    /**
     *
     * @param {Number} value  pageIndex 或者 pageIndex
     * @param {Number} type 为0标识为 pageIndex,为1标识 pageSize
     */
    onPageSelect = (value, type) => {
        let queryParam = deepClone(this.props.queryParam);
        queryParam['pageParams'] = getPageParam(value, type, queryParam.pageParams);
        this.setState({ selectedIndex: 0 }); //默认选中第一行
        actions.ActivityPlanTemplate.loadList(queryParam);
    }

    /**
     *
     * @param {Number} btnFlag 弹框框状态 0为添加、1为修改、2为详情
     */
    onClickShowModel = (btnFlag, childType, index = -1, record = {}) => {
        let { rowData } = this.props;
        if (!rowData) rowData = {}
        //let ColumnsData = eval(`this.Columns${childType}`);
        let ColumnsData = FormTableField[childType];
        this.setState({
            editModelVisible: true,
            btnFlag,
            childType: childType,
            selectedIndex: index,
            currentRecord: record,
            currentlist: rowData[childType] || []
            //ColumnsData: ColumnsData
        });
    }

    /**
     * 关闭修改model
     */
    onCloseEdit = (data, childTypeback) => {
        let { childType, btnPageFlag, selectedIndex, btnFlag } = this.state;
        let childTypetemp = childTypeback || childType
        let {  rowData } = this.props;
        this.setState({
            editModelVisible: false,
            btnFlag: -1,
        });
        if (!data) return;
        if (!rowData) rowData = {};
        
        if (btnFlag == 0 && !rowData[childTypetemp]) {
            rowData[childTypetemp] = [];
        }

        if(btnPageFlag != 0){
            this.saveFile(rowData);
        } 
        actions.ActivityPlanTemplate.updateState({rowData: rowData });
        this.forceUpdate();

    }

    /**
     *
     * @param {Number} type 1、取消 2、确定
     * @returns {Promise<void>}
     */
    confirmGoBack(type) {
        this.setState({ delModalVisible: false });
        let tempRowData;
        if (type === 1) { // 确定
            const { currentlist, childType, selectedIndex, currentRecord, search_id,btnPageFlag } = this.state;
            const { newRowData, rowData } = this.props;
            tempRowData = cloneDeep(rowData);
            actions.ActivityPlanTemplate.updateState({ newRowData: newRowData, rowData: tempRowData });
        }
    }

    /**
     * 删除modal 显示
     */
    onClickDel = (childType, record, selectedIndex) => {
        this.setState({
            delModalVisible: true,
            editModelVisible: false,
            selectedIndex: selectedIndex,
            currentRecord: record,
            childType: childType
        });
    }

    //拼接下级级联的上级参数值
    calcuParm = (item, data, fieldName, childType) => {
        let { refStateParam } = this.state;
        let tempParam = {};
        let cascadeName = item.cascadeName;
        // let param = item.param;
        // if(!param)  param={};
        if (!cascadeName) return param;
        //待优化 先取一个级联参数
        let paramName = cascadeName[0];

        tempParam[paramName] = data[0] && data[0].refpk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({ refStateParam });
    }
    //重置下级级联参照
    resetOfferRef = (item, childType, childRowData) => {
        if (!item.offers) return;
        let param = {}
        param[item.offers] = null;
        //重置级联下级参照值
        this.props.form.setFieldsValue(param);
    }

    getRefParam = (item, childType) => {
        let { refStateParam } = this.state;
        let cascadeName = item.cascadeName;
        if (!cascadeName) return {};
        let {
            alias,
        } = cascadeName;
        let _thisParmField = `${alias}_${childType}`;
        Object.keys(refStateParam).forEach(function (key) {
            if (key == _thisParmField) {
                return refStateParam[_thisParmField];
            }
        })
        return {};
    }

    initFilterFactory = (rowData, btnPageFlag) => {
        let childFields, controlData, value;
        let self = this;
        Object.keys(FormField).forEach(function (item) {
            childFields = FormField[item]["Field"];
            childFields.forEach((filed) => {
                controlData = rowData;
                if (item.search("DataHeader") == -1) {
                    controlData = rowData[item];
                }
                if (filed.hidecolumns) {
                    if (filed.hidecolumns.offerfields) {
                        value = rowData[filed.hidecolumns.offerfields];
                    }
                    self.hideColumnSaleorder(filed, value, true);
                }
                if (filed.cascadeChildTable) {//初始化的时候添加过滤
                    filed.cascadeChildTable.map(item => {
                        if (rowData[item.childType] && rowData[item.childType].length > 0) {
                            rowData[item.childType].map(itemdata => {
                                if(item.dtoKey=="organizationId"){
                                    itemdata[item.dtoKey] = controlData[item.dtoKey];
                                }
                            })
                        }
                    })
                    actions.ActivityPlanTemplate.updateState({ rowData: rowData });
                }
                ControlCommonFor1909(controlData, filed, btnPageFlag, self, true,{ bakFormField: FormField, bakFormTableField: FormTableField, bakchildTableColumn: childTableColumn });
            })
        })
    }

    disabledDate = (current, disabledDate) => {
        if (disabledDate) {
            let tempTime = this.props.form.getFieldValue(disabledDate);
            return current && current.valueOf() < tempTime;
        }
    }

    renderFormItem = (ColumnsData, childRowData = {}, childType) => {
        let { getFieldProps, getFieldError } = this.props.form;
        let { childTableColumn, FormField, FormTableField } = this.state;
        let { selectDataList = {} } = this.props;
        let { btnPageFlag } = this.state;
        let dom = [];
        let enname, codename, showname, required, hidepage, showpage;
        let self = this;

        ColumnsData && ColumnsData.forEach((item, index) => {
            enname = childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`;
            required = item.required;
            hidepage = item.hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            switch (item.type) {
                case 'FormControl':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        size={item.componentClass && "md"}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <FormControl
                            key={`${item.enname}${index}`}
                            componentClass={item.componentClass || "input"}
                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData[item.enname] || "",
                                rules: [
                                    {
                                        required: required,
                                        message: "请输入",
                                    },
                                    {
                                        pattern: item.pattern || /^[\w\W]{0,100}$/,
                                        message:<span>{item.message || "超长度"}</span>,
                                    }
                                ],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'InputNumber':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <InputNumber toThousands={true}
                            key={`${item.enname}${index}`} max={item.max}
                            min={item.min || 0} step={item.step || 1} precision={item.precision || 2}
                            iconStyle="one" step={1} disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData[item.enname],
                                rules: [{ required: required, message: "请输入" }],
                            })}
                        />

                    </FormItem>);
                    break;
                case 'DatePicker':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <DatePicker
                            key={`${item.enname}${index}`}
                            disabledDate={(current) => self.disabledDate(current, item.disabledDate)}
                            className='form-item' format={item.format || format} disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData && childRowData[item.enname] && moment(childRowData[item.enname]),
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RangePicker':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <RangePicker
                            key={`${item.enname}${index}`}
                            dateInputPlaceholder={['开始', '结束']}
                            disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: [moment(), moment()],
                                rules: [{ required: required, message: '请选择', }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RefComponent':
                    //this.initFilterFactory(item,childRowData);
                    showpage && dom.push(<FormItem
                        className="time"
                        ref={item.enname}
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <RefComponent
                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            multiple={item.multiple || false}
                            key={`${item.enname}${index}`}
                            constparam={item.param}
                            aliasparam={self.state.refStateParam}
                            aliasfieldName={item.alias}
                            title={item.zhname}
                            refName={item.refname}
                            childType={childType}
                            fieldName={enname}
                            clearMatchData={this.clearMatch}
                            rules={[
                                {
                                    required: required,
                                    message: '请选择',
                                    pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                }
                            ]}
                            initialValue={initValueString(
                                childRowData[item.showname],
                                childRowData[item.enname],
                                item.required,
                                childRowData[item.codename],
                            )}
                            refTableOnClickSave={(refName, fieldName, data) => {
                                ControlCommonFor1909(data[0], item, btnPageFlag, self);
                                if (item.relation && data[0]) {
                                    resetOfferRefCommon(self, item.relation, data, childType);
                                }
                                if (item.hidecolumns) {
                                    self.hideColumnSaleorder(item, data);
                                }
                            }}
                            refTreeOnClickSave={(refName, fieldName, data) => {

                                ControlCommonFor1909(data[0], item, btnPageFlag, self);

                                if (item.relation && data[0]) {
                                    resetOfferRefCommon(self, item.relation, data, childType);
                                }
                                if(item.enname=="customerCategoryId"){
                                    let value = data[0] && data[0].refcode || "";
                                    self.hideAll(value,data[0]||{});
                                }else{
                                    ControlCommonFor1909(data[0], item, btnPageFlag, self);
                                }
                               
                            }}
                            form={self.props.form}
                        />
                    </FormItem>);
                    break;
                case 'Select':
                    let options = selectDataList[item.code] || item.options;
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(childType.search("DataHeader") == -1 ? `${childType}.${item.codename}` : `${item.codename}`)} />}
                        label={item.zhname}
                    >
                        <Select
                            key={`${item.enname}${index}`}
                            onSelect={(value, props) => {
                                onChangeSelect(self, props, item, childType);
                                if (item.relation && value) {
                                    resetOfferRefCommon(self, item.relation, value, childType);
                                }
                                ControlCommonFor1909(value, item, btnPageFlag, self);
                            }}
                            disabled={item.disablecontrol && item.disablecontrol[btnPageFlag] || !item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {
                            ...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.codename}` : `${item.codename}`, {
                                initialValue: renderSelectInit(childRowData[item.codename], item.defaultValue),
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })
                            }
                        >
                            <Option value="">请选择</Option>
                            {
                                options && options.map((item, index) => {
                                    return (
                                        <Option key={`${item.code}${index}`} id={item.id} value={item.code}>{item.name}</Option>
                                    )
                                })
                            }

                        </Select>
                        <FormControl className="hide"
                            {...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.showname}` : `${item.showname}`, {
                                initialValue: childRowData[`${item.showname}`] || "",
                            })}
                        />
                        <FormControl className="hide"
                            {...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`, {
                                initialValue: childRowData[`${item.enname}`] || "",
                            })}
                        />
                    </FormItem>);
                    break;
                case 'Radio':

                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <Radio.RadioGroup
                            key={`${item.enname}${index}`}
                            //className={(!item.edit || btnPageFlag ==2) && "disabled"}
                            {
                            ...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`, {
                                initialValue: renderRadioInit(childRowData[item.enname], item.defaultValue),
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            }
                            )}
                        >
                            {
                                item.options && item.options.map((itemoption, index) => {
                                    return (
                                        <Radio
                                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5}
                                            key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                    )
                                })
                            }
                        </Radio.RadioGroup>
                    </FormItem>);
                    break;
                default: break;
            }
        })
        return dom;
    }

    //同步NCC
    // syncNCC = () => {
    //     let self = this;
    //     let { rowData } = self.props;
    //     actions.ActivityPlanTemplate.syncNCC(rowData.id);
    // }
    syncNCC = () => {
        let self = this;
        let { rowData } = self.props;
        // rowData.costCalculationTypeCode = rowData.costCalculationTypeCode && rowData.costCalculationTypeCode.join(',');
        actions.ActivityPlanTemplate.syncNCC(rowData);
    }

    //详情页的编辑和复制转换
    onToEdit = (type) => {
        let self = this;
        return () => {
            let { rowData } = this.props;
            if(type == 3) {
                rowData = this.copyDataDeal(rowData);
            }
            this.initFilterFactory(rowData, type);
            this.setState({ btnPageFlag: type, FormField: FormField });
            
        }
    }

    
    //虚拟关联方的时候 只有供应商名称和供应商基本分类可以显示
    hideAll = (value,data) =>{
        let searchObj = queryString.parse(this.props.location.search);
        let { btnPageFlag } = searchObj;
        let { rowData } = this.props;
        let assignRowData=cloneDeep(rowData);
        let formValue = this.props.form.getFieldsValue();
        formValue = onHandleChildObj(formValue, btnPageFlag, null);
        assignRowData = Object.assign({}, assignRowData, formValue.values);
        assignRowData.customerCategoryId = data.refpk;
        assignRowData.customerCategoryCode = data.refcode;
        assignRowData.customerCategoryName = data.refname;
        
        
        if(value == "03"){
            this.initFilterFactory(assignRowData,4);
            this.setState({ btnPageFlag: 4 })
            
        }else{
            if(btnPageFlag == 2 || btnPageFlag == 4) btnPageFlag = 1;
            this.initFilterFactory(assignRowData,btnPageFlag)
            this.setState({ btnPageFlag: btnPageFlag });
        }
    }

    //详情页的编辑和复制转换
    // onToEdit = (type) => {
    //     return () => {
    //         if (type == 3) {
    //             let { search_id } = this.state;
    //             let param = { id: search_id, type: "0" };
    //             actions.ActivityPlanTemplate.queryDetail(param);
    //         }
    //         this.setState({ btnPageFlag: type })
    //     }
    // }

    //详情页的删除操作
    onDel = () => {
        let { search_id } = this.state;
        actions.ActivityPlanTemplate.delItem({
            ids: search_id
        });
        actions.routing.goBack();
    }

    hideColumnSaleorder = (item, data, initFlag) => {
        let hidecolumns = item.hidecolumns;
        let self = this;
        let value, flag;;
        if (initFlag || item.type != "RefComponent" || !data[0]) {
            value = data
        } else if (item.type == "RefComponent") {
            value = data[0][hidecolumns.currentkey];
        }

        if (hidecolumns.show) {
            if (typeof value == "number") {
                flag = hidecolumns.value != value;
            } else {
                flag = hidecolumns.value.search(value) == -1
            }

        } else {
            if (typeof value == "number") {
                flag = hidecolumns.value == value;
            } else {
                flag = hidecolumns.value.search(value) !== -1
            }
        }
        self.hideColumnCommon(flag, hidecolumns.columns);
    }

    hideColumnCommon = (flag, showFileds) => {
        let { childTableColumn } = this.state;
        childTableColumn.mrjtCustomerAddressList.column.map(item => {
            if (showFileds.indexOf(item.dataIndex) !== -1) {
                item.hideField = flag
            }
        })
        this.setState(childTableColumn);
    }

    renderFormFiled = () => {
        let { rowData = {} } = this.props;
        let { btnPageFlag } = this.state;
        let { FormField } = this.state;
        let authCodeList = JSON.parse(sessionStorage.getItem("ActivityPlanTemplate") || "[]");
        let FormDom = [];
        let hidePanel;
        let hidepage, showpage;
        //if(!isEmptyObj(rowData)) return FormDom;
        for (let item in FormField) {
            let renderData;
            if (item.search("DataHeader") != -1) {
                renderData = rowData;
            }
            // else if (item == "mrjtCustomerCompanyDataHeader" && isEmptyObj(fbmrjtCustomerCompanyDataHeader)) {
            //     renderData = fbmrjtCustomerCompanyDataHeader;
            // }
            else {
                renderData = rowData && rowData[item] || {};
            }

            hidepage = FormField[item].hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            hidePanel = false;
            if(btnPageFlag==1 && item=="DataHeader" && authCodeList.indexOf("9901-05-03-21") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerCompanyDataHeader" && authCodeList.indexOf("9901-05-03-18") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerCredit" && authCodeList.indexOf("9901-05-03-19") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerFactoryInformationListDataHeader" && authCodeList.indexOf("9901-05-03-20") == -1){
                hidePanel=true;
            }

            if (showpage) {
                FormDom.push(<CollapsePanel in={true} key={FormField[item].title} title={FormField[item].title}>
                    <FormList size="sm">
                        {this.renderFormItem(FormField[item].Field, renderData, item)}
                    </FormList>
                </CollapsePanel>)
            }
        }
        return FormDom;
    }

    //启用
    ButtonEnable = (item, index, record) => {
        let { rowData } = this.props;
        let url;
        if (item == "mrjtCustomerAddressList") {
            url = "customer-address/batch-enable";
        } else if (item == "mrjtCustomerFinanceList") {
            url = "customer-finance/batch-enable";
        } else if (item == "mrjtCustomerContactList") {
            url = "customer-contact/batch-enable"
        }else if(item == "mrjtCustomerAccountList") {
            url = "customer-account/batch-enable"
        }

        let param = {
            data: {
                ids: record.id || "1"
            },
            header: {
                url: url,
                method: 'post',
                ContentType: 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }
        actions.ActivityPlanTemplate.ButtonSetsModel(param);

        rowData[item][index].isEnable = 1;
    }

    //停用
    ButtonDisable = (item, index, record) => {
        let { rowData } = this.props;
        let url;
        if (item == "mrjtCustomerAddressList") {
            url = "customer-address/batch-disable";
        } else if (item == "mrjtCustomerFinanceList") {
            url = "customer-finance/batch-disable";
        } else if (item == "mrjtCustomerContactList") {
            url = "customer-contact/batch-disable"
        }else if(item == "mrjtCustomerAccountList") {
            url = "customer-account/batch-disable"
        }
        let param = {
            data: {
                ids: record.id || "1"
            },
            header: {
                url: url,
                method: 'post',
                ContentType: 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }
        actions.ActivityPlanTemplate.ButtonSetsModel(param);

        rowData[item][index].isEnable = 2;
    }

    saveFile = (rowData) => {
        let { search_id } = this.state;
        let param = {
            data: search_id || rowData.id,
            file: rowData
        }
        actions.ActivityPlanTemplate.submitFile(param);
    }

    checkFile = (record) => {
        let url =  record.fileUrl + `?attname=${record.filename}`;
        window.open(url);
    }

    renderaliaCustomer = (fieldName, data) => {
        actions.ActivityPlanTemplate.getAliaCustomer(data[0].id);
    }

    renderTableFiled = () => {
        let { rowData, showLoading, aliaCustomerList } = this.props;
        let authCodeList = JSON.parse(sessionStorage.getItem("ActivityPlanTemplate") || "[]");
        let { personName } = this.props.personData
        let searchObj = queryString.parse(this.props.location.search);
        let { getDealFlag } = searchObj;
        let { childTableColumn, FormField, FormTableField } = this.state;
        let { tableHeight, btnPageFlag } = this.state;
        let hidepage, showpage, hideBtns = {};
        let type, tempColumn, _column, gridData;
        let FormDom = [];
        let sortObj = {
            mode: 'multiple',
            backSource: true
        }
        if (!rowData) rowData = {};

        let _this = this;

        let groupname;
        if (btnPageFlag == 0) {
            groupname = sessionStorage.getItem("uui");
        }else {
            groupname = rowData.id;
        }
        //文件上传
        const fileUpload = {
            name: 'fileList',
            action: '/iuap-saas-filesystem-service/file/upload',     //上传地址
            data: { 
                groupname: groupname, 
                filepath: groupname, 
                url: true, 
                isreplace: false 
            },
            headers: {
            },
            showUploadList: false,
            beforeUpload(file) {
                var fileSize = file.size / (1024 * 1024)
                if(fileSize>11) {
                    Message.create({ content: "文件大小不能超过11MB！", color: 'warning', duration: 10 });
                    return false
                }
                if(this.splitFileName(file.name).length>20) {
                    Message.create({ content: "文件名不能超过20个字", color: 'warning', duration: 10 });
                    return false
                }
            },
            splitFileName(text) {//用正则表达式去去除文件后缀
                var pattern = /\.{1}[a-z]{1,}$/;
                if (pattern.exec(text) !== null) {
                    return (text.slice(0, pattern.exec(text).index));
                } else {
                    return text;
                }
            },
            onChange(info) {
                if (info.file.status !== 'uploading') {
                }
                if (info.file.status === 'done') {
                    let res = info.file.response;
                    if (res.status == 0) {
                        Message.create({ content: res.message, color: 'danger', duration: 10 });
                        return;
                    }
                    let name = info.file.name.split(".");
                    let type = name[name.length - 1];
                    let { filename, uploadtime, url } = res.data[0];
                    let fileData = {
                        filename: filename,
                        creationTime: new Date(uploadtime).getTime(), //uploadtime
                        creator: personName,
                        fileUrl: url,
                        type: type,
                        persistStatus: "new"
                    }
                } else if (info.file.status === 'error') {

                }
            }
        };

        Object.keys(childTableColumn).forEach(function (item) {

            let dom;
            hidepage = childTableColumn[item].hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            tempColumn = cloneDeep(childTableColumn[item]);
            type = childTableColumn[item].type;
            if (showpage && type == "grid") {
                gridData = rowData[item] || [];
                if (!rowData[item]) rowData[item] = [];
                _column = tempColumn && tempColumn.column || {};
                btnPageFlag = _this.state.btnPageFlag;
                hideBtns = {};
                
                if (getDealFlag == "true") {
                   
                    if (gridData.length > 0) {
                        gridData.map(item => {
                            item.editFlagObj = { 
                                activityStartDate: false, 
                                activityEndDate: false, 
                                customerName: false,
                                channelTypeName: false,
                                saleTypeCode: false,
                                actualSaleAmount: true, 
                                actualCostAmount: true,  
                                actualCostAmount1: true,
                                actualCostRate: true,  
                                saleCompletionRate: true,   
                                brief: true,   
                            };
                            // item.editFlagObj.activityStartDate = true;
                            // item.editFlagObj.activityEndDate = true;
                            // item.editFlagObj.customerName = true;
                            // item.editFlagObj.channelTypeName = true;
                            // item.editFlagObj.saleTypeCode = true;
                        })
                    }
                    hideBtns = { "copy": true };
                }

                dom = <div className="gird-parent">
                    <EditGrid
                        showIndex={true}
                        disabled={btnPageFlag == 2}
                        btnPageFlag={btnPageFlag}
                        defaultOpen={true}
                        columns={_column}
                        data={gridData}
                        childType={item}
                        hideBtns={hideBtns}
                        paginationObj={"none"}
                        multiSelect={true}
                        onChange={_this.onEditGridChange}
                        defaultValueObj={childTableColumn[item].defaultValueObj}
                        showPagination={false}
                        onValidate={onEditGridValidate}
                        onDel={_this.onEditGridDel}
                        beforeAddRow={_this.beforeAddRow}
                        loading={{ show: showLoading }}
                    />

                    {/* <Grid
                        ref={(el) => _this.grid = el} //存模版
                        data={rowData[item]}
                        rowKey={Math.random()}
                        columns={_column}
                        paginationObj={'none'}
                        multiSelect={false}
                        showHeaderMenu={true}
                        sort={sortObj} //后端排序
                        loading={{ show: showLoading, }}
                        scroll={{ y: tableHeight }}
                        sheetHeader={{ height: 30, ifshow: false }}
                    /> */}
                </div>;
                FormDom.push(<CollapsePanel in={!tempColumn.collapse} key={tempColumn.title} title={tempColumn.title}>
                    {dom}
                </CollapsePanel>)
            } else if (showpage && type == "table") {
                let tableData = rowData[item] || [];

                // if (item == "relateCustomerList" && aliaCustomerList) {
                //     tableData = aliaCustomerList;
                // }
                dom = <Grid
                    paginationObj={'none'}
                    multiSelect={false}
                    data={tableData}
                    rowKey={(r, i) => i}
                    columns={tempColumn.column}
                />;
                FormDom.push(<CollapsePanel in={!tempColumn.collapse} key={tempColumn.title} title={tempColumn.title}>
                    {dom}
                </CollapsePanel>)
            }
        })

        console.log(FormDom);
        return FormDom;
    }

    ButtonApprovalCal = () => {
        let searchObj = queryString.parse(this.props.location.search);
        let { from } = searchObj; 
        if(from == "approveCenter") {
            let data = {
                id: "approveCenter",
                router: "/mcc-portal-react/base/index.html#approveCenter",
                title: "审批任务"
            }
            window.top.handleClick(null,1,data);
        }else if( from == "messageCenter") {
            let data = {
                id: "messageCenter2",
                router: "/mcc-portal-react/base/index.html#messageCenter",
                title: "消息列表"
            }
            window.top.handleClick(null,1,data);
        }else {
            actions.routing.push(
                {
                    pathname: '/ActivityPlanTemplate-list',
                }
            )
        }
        
    }

    beforeAddRow = (childType, callback) => {
        let { form, rowData } = this.props;
        let values = form.getFieldsValue(["organizationId"]);
        let data = onHandleChildObj(values, "0").values;
        callback && callback({ [childType]: data });
    }

    render() {
        let { editModelVisible, selectedIndex, btnFlag, tableHeight, search_id,
            delModalVisible, currentlist, ColumnsData, btnPageFlag, childType } = this.state;
        let { childTableColumn, FormField, FormTableField } = this.state;
        let {rowData} = this.props;
        let authCodeList = JSON.parse(sessionStorage.getItem("ActivityPlanTemplate") || "[]");
        let sortObj = {
            mode: 'multiple',
            backSource: true
        }
        if(typeof btnPageFlag == "undefined") {return <></>};
        let rowDataArray = [];
        rowDataArray.push(this.props.rowData);
        let { getFieldProps } = this.props.form;
        let bpmService = {
            "ButtonSubmit": {
                url: `/occ-fee/fee/expense-summary/batch/submit?billCode=billCode`,
                code: "0",  //自由
                field: "state",
                authCode: "ActivityPlanTemplatesubmit",
            },
            "ButtonCallback": {
                url: `/occ-fee/fee/expense-summary/batch/taskback`,
                code: "1",
                field: "state",
                authCode: "ActivityPlanTemplatereject",
            },
            "ButtonApprove": {
                url1: `/occ-fee/fee/expense-summary/batch/complete?billCode=billCode`,
                url: `/occ-fee/fee/expense-summary/batch/judgeProcess`,
                code: "1,2",
                field: "state",
                authCode: "ActivityPlanTemplateapprove",
            },
            "ButtonCancelApprove": {
                url: `/occ-fee/fee/expense-summary/batch/withdrawtask`,
                code: "2,3",
                field: "state",
                authCode: "ActivityPlanTemplatecancel",
            },
            "CheckApprove": {
                url: `/occ-cmpt/bpm/processoper/historictasks`,
                code: "0,1,2,3",
                field: "state",
                authCode: "ActivityPlanTemplatereject",
            }
        }
        let pagetitle = this.onChangeHead(btnPageFlag);
        return (
            <div className='single-table-popup ActivityPlanTemplate-detail'>

                <Header title={pagetitle} back={true} backFn={this.onBack}>
                    {(btnPageFlag != 2 && btnPageFlag != 5) ? (
                        <div className='head-btn'>
                            <Button className='head-save' onClick={this.onBack}>取消</Button>
                            <Button className='head-save' onClick={this.save}>保存</Button>
                        </div>
                    ) : (<div className='head-btn'>
                        {authCodeList.indexOf("9901-05-03-06")!==-1 && btnPageFlag != 5 && <Button className='head-cancel' onClick={this.onToEdit(1)}>编辑</Button>}
                        <DelModal selectData={[{}]} modalTitle="删除" modalContent="确认删除？" confirmFn={this.onDel}>
                        {authCodeList.indexOf("9901-05-03-07")!==-1 && <Button className='head-save'>删除</Button>}
                        </DelModal>
                        {/* <Button className='head-save' onClick={this.onToEdit(3)}>复制</Button> */}
                        {/* <Button className='head-save' onClick={this.syncNCC}>同步NCC</Button> */}
                        {/* {<Button className='head-save' onClick={this.syncNCC}>更新销售数据</Button>} */}
                        <PurchaseApprovalButton
                            selectData={rowDataArray}
                            billType="CUAP"
                            printTemplateId="1001A61000000001R3LU"
                            ButtonApprovalCal={this.ButtonApprovalCal}
                            authCodeList={authCodeList}
                            modalName = "ActivityPlanTemplate"
                            bpmService={bpmService}
                        />
                    </div>)
                    }
                </Header>
                {this.renderFormFiled()}
                {this.renderTableFiled()}

                <Alert show={delModalVisible}
                    context={this.state.modalContent || "确定操作？"}
                    confirmFn={() => {
                        this.confirmGoBack(1);
                    }}
                    cancelFn={() => {
                        this.confirmGoBack(2);
                    }}
                />
                <PopupModal
                    editModelVisible={editModelVisible}
                    onCloseEdit={this.onCloseEdit}
                    ColumnsData={FormTableField[childType] && FormTableField[childType].Field || []}
                    currentIndex={selectedIndex}
                    childType={childType}
                    btnFlag={btnFlag}
                    customerId={search_id}
                    list={currentlist || []}
                    personData={this.props.personData}
                    dataHeader={this.props.form.getFieldsValue()}
                    selectDataList={this.props.selectDataList}
                />
            </div >
        )

    }
}

export default Form.createForm()(Edit);


